﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Kaskelot.SP.Core
{
    public static class SPEmailHelper
    {
        public static void SendEmail( SPWeb spWeb,
                                        string to,
                                        string cc,
                                        string bcc,
                                        string subject,
                                        string body,
                                        bool isBodyHtml)
        {
            Logger.LogVerbose("SPEmailHelper", LayerNames.Services, "SendEmail", "-> Entered");

            string emailSummary;

            var messageHeaders = new StringDictionary();

            messageHeaders.Add("to", to);
            messageHeaders.Add("subject", subject);
            messageHeaders.Add("cc", cc);
            messageHeaders.Add("bcc", bcc);

            string mimeType = "text/plain";
            if (isBodyHtml)
            {
                mimeType = "text/html";
            }

            messageHeaders.Add("content-type", mimeType);

            bool sendMail = SPUtility.SendEmail(
                   spWeb,
                   messageHeaders,
                   body);

            if (sendMail)
            {
                emailSummary = "<EmailMessage>" +
                                    "<To>" + to + "</To>" +
                                    "<Subject>" +
                                        SPEncode.HtmlEncode(subject) +
                                    "</Subject>" +
                                    "<CC>" + cc + "</CC>" +
                                    "<BCC>" + bcc + "</BCC>" +
                                    "<Body>" +
                                        SPEncode.HtmlEncode(body) +
                                     "</Body>" +
                                 "</EmailMesage>";
                Logger.LogVerbose("SPEmailHelper", LayerNames.Services, "SendEmail", "E-mail was sent: " + emailSummary);
            }
            else
            {
                throw new Exception("Det gick inte att skicka mailet. Verifiera att SMTP-tjänsten är korrekt konfigurerad.");
            }

            Logger.LogVerbose("SPEmailHelper", LayerNames.Services, "SendEmail", "Exiting ->");
        }
    }
}
